package drds.plus.executor.function.scalar.subquery;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.cursor.cursor.ISortingCursor;
import drds.plus.executor.data_node_executor.DataNodeExecutorContext;
import drds.plus.executor.row_values.RowValues;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.abstract_syntax_tree.configuration.ColumnMetaData;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.query.Query;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.function.FunctionName;
import drds.tools.$;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;


@Slf4j
public class ListSubQuery extends AbstractSubQueryFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        Query query = this.getQuery(args);
        ISortingCursor sortingCursor = null;
        try {
            sortingCursor = DataNodeExecutorContext.getExecutorContext().getDataNodeExecutor().execute(executeContext, query);
            RowValues rowData = null;
            List<Object> objectList = new ArrayList();
            while ((rowData = sortingCursor.next()) != null) {
                ColumnMetaData columnMetaData = rowData.getParentCursorMetaData().getColumnMetaDataList().get(0);
                Object value = Utils.getValue(rowData, columnMetaData);
                objectList.add(value);
            }
            return objectList;
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        } finally {
            if (sortingCursor != null) {
                List<RuntimeException> exs = new ArrayList();
                exs = sortingCursor.close(exs);
                if ($.isNotNullAndHasElement(exs)) {
                    for (RuntimeException e : exs) {
                        log.warn("close subquery failed, exception is:");
                    }
                }
            }
        }

    }

    public String[] getFunctionNames() {
        return new String[]{FunctionName.subquery_list};
    }
}
